﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 战地2服务器控制中心
{
    public partial class Main : Form
    {
        int ServerCheck = 0;//服务器文件检测
        bool RankCheck = false;
        string mode = null;
        public Main()//构造函数
        {
            InitializeComponent();//初始化所有控件
            //检测PB文件是否存在如果存在就删除///修复PB引起的踢出问题
            try
            {
                Directory.Delete("pb", true);//适用于里面有子目录，文件的文件夹  

            }
            catch
            {

            }
            try
            {
                WebClient client = new WebClient();
                byte[] buffer = client.DownloadData("http://bf2.ttitt.net/SMD5.TTmd5");//从服务器上下载文本
                var Slines = System.Text.ASCIIEncoding.ASCII.GetString(buffer);//把下载好的文本赋值给Slines通过下标来指定
                string SMD5 = Slines.Substring(7);//已经从服务器上得到MD5值
                string BMD5 = CheckMD5.GetMD5HashFromFile("bf2_w32ded.exe");//传入本地程序并取回得到的MD5值
                if (SMD5 == BMD5)
                {
                    HostsStatusPic.Image = 战地2服务器控制中心.Properties.Resources.check;//服务器端文件匹配检测通过
                }
                else
                {
                    HostsStatusPic.Image = 战地2服务器控制中心.Properties.Resources.error;//服务器检测未通过
                    ServerCheck = 1;
                }
            }
            catch
            {
                MessageBox.Show("网络故障，请检查你的网络。或者稍后再试。");
                Process.GetCurrentProcess().Kill();
            }
            try
            {
                var Ranklines = File.ReadAllLines(@"python\bf2\BF2StatisticsConfig.py");//读取rank设置
                string _Rank = Ranklines[18];
                string Rank = _Rank.Substring(20);
                if (Rank == "'112.74.72.169'")
                {
                    StatsStatusPic.Image = 战地2服务器控制中心.Properties.Resources.check;//rank检测通过
                    RankCheck = true;
                }
                else
                {
                    StatsStatusPic.Image = 战地2服务器控制中心.Properties.Resources.error;//rank检测未通过
                    MessageBox.Show("你的军衔文件检测没有通过，建议你重新安装一次");
                    RankCheck = false;
                }
            }
            catch
            {
                MessageBox.Show("军衔文件没有安装");
                RankCheck = false;
            }
            ServerStatusPic.Image = 战地2服务器控制中心.Properties.Resources.error;//服务器未启动
        }

        private void EditServerSettingsBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (ServerCheck == 1)//判断服务器端检测
                {
                    MessageBox.Show("你服务器端检测未通过");
                    DialogResult dr = MessageBox.Show("检测到你的服务器端不匹配，是否进行自动更新", "文件不匹配警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dr == DialogResult.OK)
                    {
                        MessageBox.Show("服务器端正在更新，请稍等！");
                        EditServerSettingsBtn.Enabled = false;
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://bf2.ttitt.net/updata/bf2_w32ded.exe");//下载服务器上的服务器端文件
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                        Stream responseStream = response.GetResponseStream();
                        Stream stream = new FileStream(@"bf2_w32ded.exe", FileMode.Create);
                        byte[] bArr = new byte[1024];
                        int size = responseStream.Read(bArr, 0, bArr.Length);
                        while (size > 0)
                        {
                            stream.Write(bArr, 0, size);
                            size = responseStream.Read(bArr, 0, bArr.Length);
                        }
                        stream.Close();
                        responseStream.Close();
                        MessageBox.Show("服务器端更新完毕,请重启控制中心");
                        EditServerSettingsBtn.Enabled = true;
                        Process.GetCurrentProcess().Kill();
                    }
                    else
                    {
                        //Close();
                    }

                }
                else
                {
                    服务器设置 SS = new 服务器设置();
                    SS.ShowDialog();
                }
            }
            catch { }
        }

        private void LaunchServerBtn_Click(object sender, EventArgs e)
        {
            if (File.Exists(@"bf2_w32ded.exe"))
            {
                StopServer.Visible = true;
                LaunchServerBtn.Visible = false;
                ServerStatusPic.Image = 战地2服务器控制中心.Properties.Resources.check;//服务器启动
                System.Diagnostics.Process.Start("bf2_w32ded.exe");
            }
            else
            {
                MessageBox.Show("请放入战地2根目录下");
            }
        }

        private void StopServer_Click(object sender, EventArgs e)
        {
            Process[] processes = Process.GetProcessesByName("bf2_w32ded");
            foreach (Process p in processes)
            {
                if (System.IO.Path.Combine(Application.StartupPath, "bf2_w32ded.exe") == p.MainModule.FileName)
                {
                    p.Kill();
                    p.Close();
                }
            }
            StopServer.Visible = false;
            LaunchServerBtn.Visible = true;
            ServerStatusPic.Image = 战地2服务器控制中心.Properties.Resources.error;//服务器未启动
        }

        private void EditMapListBtn_Click(object sender, EventArgs e)//打开地图设置
        {
            地图设置 SS = new 地图设置();
            SS.ShowDialog();
        }

        private void BF2sInstallBtn_Click(object sender, EventArgs e)//安装军衔
        {

            if (RankCheck == false)
            {
                try
                {
                    //添加rank文件
                    //init.py
                    byte[] init = global::战地2服务器控制中心.Resources.Rank.__init__;
                    File.WriteAllBytes(@"python\bf2\__init__.py", init);
                    //BF2StatisticsConfig.py
                    byte[] BF2StatisticsConfig = global::战地2服务器控制中心.Resources.Rank.BF2StatisticsConfig;
                    File.WriteAllBytes(@"python\bf2\BF2StatisticsConfig.py", BF2StatisticsConfig);
                    //ClanManager.py
                    byte[] ClanManager = global::战地2服务器控制中心.Resources.Rank.ClanManager;
                    File.WriteAllBytes(@"python\bf2\ClanManager.py", ClanManager);
                    //GameLogic.py
                    byte[] GameLogic = global::战地2服务器控制中心.Resources.Rank.GameLogic;
                    File.WriteAllBytes(@"python\bf2\GameLogic.py", GameLogic);
                    //gui_log.pyw
                    byte[] gui_log = global::战地2服务器控制中心.Resources.Rank.gui_log;
                    File.WriteAllBytes(@"python\bf2\gui_log.pyw", gui_log);
                    //ObjectManager.py
                    byte[] ObjectManager = global::战地2服务器控制中心.Resources.Rank.ObjectManager;
                    File.WriteAllBytes(@"python\bf2\ObjectManager.py", ObjectManager);
                    //pid.txt
                    byte[] pid = global::战地2服务器控制中心.Resources.Rank.pid;
                    File.WriteAllBytes(@"python\bf2\pid.txt", pid);
                    //PlayerManager.py
                    byte[] PlayerManager = global::战地2服务器控制中心.Resources.Rank.PlayerManager;
                    File.WriteAllBytes(@"python\bf2\PlayerManager.py", PlayerManager);
                    //Timer.py
                    byte[] Timer = global::战地2服务器控制中心.Resources.Rank.Timer;
                    File.WriteAllBytes(@"python\bf2\Timer.py", Timer);
                    //TriggerManager
                    byte[] TriggerManager = global::战地2服务器控制中心.Resources.Rank.TriggerManager;
                    File.WriteAllBytes(@"python\bf2\TriggerManager.py", TriggerManager);
                    //stats __init__.py
                    byte[] statsinit = global::战地2服务器控制中心.Resources.Rank.__init__1;
                    File.WriteAllBytes(@"python\bf2\stats\__init__.py", statsinit);
                    //constants.py
                    byte[] constants = global::战地2服务器控制中心.Resources.Rank.constants;
                    File.WriteAllBytes(@"python\bf2\stats\constants.py", constants);
                    //endofround.py
                    byte[] endofround = global::战地2服务器控制中心.Resources.Rank.endofround;
                    File.WriteAllBytes(@"python\bf2\stats\endofround.py", endofround);
                    //fragalyzer_log.py
                    byte[] fragalyzer_log = global::战地2服务器控制中心.Resources.Rank.fragalyzer_log;
                    File.WriteAllBytes(@"python\bf2\stats\fragalyzer_log.py", fragalyzer_log);
                    //medal_data.py
                    byte[] medal_data = global::战地2服务器控制中心.Resources.Rank.medal_data;
                    File.WriteAllBytes(@"python\bf2\stats\medal_data.py", medal_data);
                    //medal_data_xpack.py
                    byte[] medal_data_xpack = global::战地2服务器控制中心.Resources.Rank.medal_data_xpack;
                    File.WriteAllBytes(@"python\bf2\stats\medal_data_xpack.py", medal_data_xpack);
                    //medals.py
                    byte[] medals = global::战地2服务器控制中心.Resources.Rank.medals;
                    File.WriteAllBytes(@"python\bf2\stats\medals.py", medals);
                    //miniclient.py
                    byte[] miniclient = global::战地2服务器控制中心.Resources.Rank.miniclient;
                    File.WriteAllBytes(@"python\bf2\stats\miniclient.py", miniclient);
                    //rank.py
                    byte[] rank = global::战地2服务器控制中心.Resources.Rank.rank;
                    File.WriteAllBytes(@"python\bf2\stats\rank.py", rank);
                    //snapshot.py
                    byte[] snapshot = global::战地2服务器控制中心.Resources.Rank.snapshot;
                    File.WriteAllBytes(@"python\bf2\stats\snapshot.py", snapshot);
                    //stats.py
                    byte[] stats = global::战地2服务器控制中心.Resources.Rank.stats;
                    File.WriteAllBytes(@"python\bf2\stats\stats.py", stats);
                    //unlocks.py
                    byte[] unlocks = global::战地2服务器控制中心.Resources.Rank.unlocks;
                    File.WriteAllBytes(@"python\bf2\stats\unlocks.py", unlocks);
                    //创建文件夹
                    Directory.CreateDirectory(@"python\bf2\logs\snapshots\sent");
                    Directory.CreateDirectory(@"python\bf2\logs\snapshots\unsent");
                    //DELETE_ME
                    byte[] DELETE_ME = global::战地2服务器控制中心.Resources.Rank.DELETE_ME;
                    File.WriteAllBytes(@"python\bf2\logs\snapshots\sent\DELETE_ME", DELETE_ME);
                    File.WriteAllBytes(@"python\bf2\logs\snapshots\unsent\DELETE_ME", DELETE_ME);
                    RankCheck = true;//切换标记头
                    MessageBox.Show("安装完成");
                    StatsStatusPic.Image = 战地2服务器控制中心.Properties.Resources.check;//rank检测通过
                }
                catch
                {
                    MessageBox.Show("你的战地2文件有损坏，请下载正规的战地2");
                }
            }
            else
            {
                MessageBox.Show("你已经安装了军衔文件，无需再次安装");
            }
        }
        /// <summary>
        /// 主窗口加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_Load(object sender, EventArgs e)
        {
            DirectoryInfo Folder = new DirectoryInfo(@"mods");
            foreach (DirectoryInfo NextFolder in Folder.GetDirectories())
            {
                this.cbbMZ.Items.Add(NextFolder.Name);
            }
        }
        /// <summary>
        /// 选择模组
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbbMZ_SelectedIndexChanged(object sender, EventArgs e)
        {
            EditServerSettingsBtn.Enabled = true;
            EditMapListBtn.Enabled = true;
            BF2sInstallBtn.Enabled = true;
            LaunchServerBtn.Enabled = true;
            mode = cbbMZ.Text;
            SupportMode.Mode = mode;
        }
        /// <summary>
        /// 高级设置,设置如双倍载具，无限体力，无限载具，这类的高级参数等。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BTgjsetting_Click(object sender, EventArgs e)
        {
            //using (ZipFile zip = new ZipFile(@"mods\bf2\Levels\Dalian_Plant\1.zip", Encoding.Default))//创建对象，设置路径和编码格式
            //{
            //    zip.AddFile(@"1.txt",@"1\2\");//添加要压缩的文件并且指定要添加到的目录
            //    zip.Save();//保存压缩文件
            //}
            高级设置 SS = new 高级设置();
            SS.Show();
        }
    }
}
